package com.edu.whty.service.base.impl;

import com.edu.whty.common.tools.GUIDGenerator;
import com.edu.whty.dao.PlatformModelDao;
import com.edu.whty.dao.system.SysConfigDao;
import com.edu.whty.dao.system.SysDomainDao;
import com.edu.whty.entity.system.TbSysEduResPlatform;
import com.edu.whty.entity.system.*;
import com.edu.whty.service.base.ConfigService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 多平台配置Service
 *
 * @author shijiapeng
 * @date 2015年8月24日 下午6:45:20
 */
@Service("configService")
public class ConfigServiceImpl implements ConfigService {
    public static final String KEY_LIST = "queryChapters,query_chapters,query_editions,query_periods,query_subjects,query_textbooks,query_volumes";
    public static final String DOMAIN_START = "http://";

    @Resource
    private SysConfigDao sysConfigDao;
    @Resource
    private SysDomainDao sysDomainDao;
    @Resource
    private PlatformModelDao platformModelDao;

    /**
     * 获取一条配置，如果有多条取第一条
     *
     * @param platformCode
     * @param keyName
     * @return
     * @throws Exception
     */
    @Override
    public SysConfigPo loadSysConfigPo(String domain, String keyName) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("domain", domain);
        paramMap.put("keyName", keyName);

        return sysConfigDao.loadOneByPlatformCodeAndKeyName(paramMap);
    }

    @Override
    public List<SysDomain> listAllSysDomain() throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();

        return sysDomainDao.listByCondition(paramMap);
    }

    /**
     * 按条件获取平台配置
     *
     * @return
     */
    @Override
    public List<SysConfigPo> listSysConfig(Map<String, Object> paramMap) throws Exception {
        return sysConfigDao.listByCondition(paramMap);
    }

    /**
     * 按接口条件获取平台配置
     *
     * @return
     */
    @Override
    public List<SimpleConfig> listSimpleConfig(ConfigRo ro) throws Exception {

        if (StringUtils.isEmpty(ro.getDomain())) {

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String loginPlatformCode = (String) request.getAttribute("loginPlatformCode");

            //通过platformCode获取一条domain信息
            SysDomain domain = sysDomainDao.loadSysDomainByPlatformCode(loginPlatformCode);
            ro.setDomain(domain.getDomain());
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domain", ro.getDomain());

        return sysConfigDao.listSimpleConfigByCondition(paramMap);
    }

    @Override
    public String getDomainId(String domain) throws Exception {
        return sysDomainDao.getDomainId(domain);
    }

    @Override
    public String getDomainByPlatformCode(String platformCode) throws Exception {
        return sysDomainDao.getDomainByPlatformCode(platformCode);
    }

    private void saveVirtualPlatform(ConfigRequest param, String domainStr) throws Exception {
        SysDomain domain = new SysDomain();
        //保存域名主表信息
        domain.setId(GUIDGenerator.getGUID());
        domain.setCreaterId("admin");
        domain.setCreaterName("admin");
        domain.setDomain(domainStr);
        domain.setPlatformCode(param.getPlatformCode());
        domain.setDescribe(param.getDescribe());
        domain.setLoginPlatformCode(param.getLoginPlatformCode());

        sysDomainDao.save(domain);

        this.initPlatformModel(domain.getPlatformCode());

        //拷贝标准配置到新增加的域名
        String fromDomain = param.getFromDomain().trim();
        if (fromDomain.startsWith(DOMAIN_START)) {
            fromDomain = fromDomain.substring(fromDomain.indexOf(DOMAIN_START) + 7);
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", this.getDomainId(fromDomain));

        List<SysConfigPo> configList = sysConfigDao.listByCondition(paramMap);

        String aamif = "";
        for (SysConfigPo c : configList) {
            c.setId(GUIDGenerator.getGUID());
            c.setDomainId(domain.getId());
            c.setCreaterId(domain.getCreaterId());
            c.setCreaterName(domain.getCreaterName());
            c.setCreateTime(domain.getCreateTime());
            c.setUpdateTime(domain.getCreateTime());
            c.setPlatformCode(domain.getPlatformCode());
            //非表字段，但缓存时需要该字段
            c.setDomain(domain.getDomain());
            //登录平台编码
            if ("loginPlatformCode".equals(c.getKeyName())) {
                c.setValue(domain.getLoginPlatformCode());
            }

            //平台编码
            if ("platformCode".equals(c.getKeyName())) {
                c.setValue(domain.getPlatformCode());
            }

            //cms-ft地址修改
            if ("cms-ft".equals(c.getConfigType())) {
                String v = c.getValue();
                c.setValue(param.getCmsft() + v.substring(v.indexOf("/cms")));
            }
            //cms-portal地址修改
            if ("cms-portal".equals(c.getConfigType())) {
                String v = c.getValue();
                c.setValue(param.getCmsportal() + v.substring(v.indexOf("/cms")));
            }
            //cms-gateway地址修改
            if ("cms-gateway".equals(c.getConfigType())) {
                String v = c.getValue();
                if (!KEY_LIST.contains(c.getKeyName())) {
                    c.setValue(param.getCmsgateway() + v.substring(v.indexOf("/cms")));
                }
            }
            //门户空间地址修改
            if ("index-php".equals(c.getConfigType())) {
                String in = c.getValue();
                c.setValue(param.getSpaceUrl() + in.substring(in.indexOf("/index.php")));
            }
            //课程访问地址修改
            if ("serverName".equals(c.getKeyName())) {
                c.setValue(param.getCourseUrl());
            }
            if ("aamif".equals(c.getConfigType())) {
                aamif = c.getValue().substring(0, c.getValue().indexOf("/aamif"));
            }
            sysConfigDao.save(c);

        }
    }

    @Override
    public void saveVirtualPlatform(ConfigRequest param) throws Exception {
        String d = param.getSpaceUrl().trim();
        if (d.startsWith(DOMAIN_START)) {
            d = d.substring(d.indexOf(DOMAIN_START) + 7);
        }
        this.saveVirtualPlatform(param, d);
    }

    /**
     * 初始化开通栏目，默认全部开通
     *
     * @param platformCode
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private void initPlatformModel(String platformCode) throws Exception {
        Map<String, Object> param = new HashedMap();
        param.put("platformCode", platformCode);
        platformModelDao.deletePlatformModel(param);
        platformModelDao.insertPlatformModelAll(param);
    }

    /**
     * 保存域名信息，并拷贝标准模板配置
     *
     * @throws Exception
     */
    @Override
    public void saveSysDomain(SysDomain domain) throws Exception {

        //保存域名主表信息
        sysDomainDao.save(domain);

        //拷贝标准配置到新增加的域名
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(domain.getDemoDomainId())) {
            paramMap.put("domainId", SysDomain.DEFAULT_DOMAIN_ID);
        } else {
            paramMap.put("domainId", domain.getDemoDomainId());
        }

        List<SysConfigPo> configList = this.listSysConfig(paramMap);

        for (SysConfigPo c : configList) {
            c.setId(GUIDGenerator.getGUID());
            c.setDomainId(domain.getId());
            c.setCreaterId(domain.getCreaterId());
            c.setCreaterName(domain.getCreaterName());
            c.setCreateTime(domain.getCreateTime());
            c.setUpdateTime(domain.getCreateTime());
            c.setPlatformCode(domain.getPlatformCode());
            //非表字段，但缓存时需要该字段
            c.setDomain(domain.getDomain());

            sysConfigDao.save(c);
        }

        //初始化开通栏目，默认全部开通
        this.initPlatformModel(domain.getPlatformCode());
    }


    /**
     * 修改域名信息，如果platformCode修改了，则一并修改子表platformCode信息
     *
     * @param domain
     * @throws Exception
     */
    @Override
    public void updateSysDomain(SysDomain domain) throws Exception {

        //修改域名信息
        sysDomainDao.update(domain);

        //修改子表platformCode信息
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", domain.getId());
        paramMap.put("platformCode", domain.getPlatformCode());

        sysConfigDao.updateByCondition(paramMap);

    }

    /**
     * 批量修改接口地址
     *
     * @param config
     * @throws Exception
     */
    @Override
    public void updateApiAddress(SysConfigPo config) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", config.getDomainId());
        paramMap.put("configType", config.getConfigType());

        //获取分类下的配置列表
        List<SysConfigPo> configList = sysConfigDao.listByCondition(paramMap);
        for (SysConfigPo sysc : configList) {
            if (sysc.setAddressInfo(config.getAddressInfo()) > 0) {
                //修改value
                paramMap.clear();
                paramMap.put("id", sysc.getId());
                paramMap.put("value", sysc.getValue());

                sysConfigDao.updateByCondition(paramMap);
            }
        }
    }

    @Override
    public void saveSysConfig(SysConfigPo config) throws Exception {

        //如果是在模板中增加的配置，则同时其他域名也增加该配置
        if (SysDomain.DEFAULT_DOMAIN_ID.equals(config.getDomainId())) {

            Map<String, Object> paramMap = new HashMap<String, Object>();

            List<SysDomain> domainList = sysDomainDao.listByCondition(paramMap);

            for (SysDomain domain : domainList) {
                //如果不存在配置
                if (!haveExistConfig(domain.getId(), config.getKeyName())) {

                    config.setId(GUIDGenerator.getGUID());
                    config.setDomainId(domain.getId());
                    config.setDomain(domain.getDomain());
                    config.setPlatformCode(domain.getPlatformCode());

                    //自动设置可能的接口地址
                    if (config.getValue().startsWith("http")) {
                        paramMap.put("domainId", domain.getId());
                        paramMap.put("configType", config.getConfigType());

                        SysConfigPo demo = sysConfigDao.loadByCondition(paramMap);
                        if (demo != null && StringUtils.isNotEmpty(demo.getAddressInfo())) {
                            config.setAddressInfo(demo.getAddressInfo());
                        }
                    }

                    sysConfigDao.save(config);
                }
            }

        }

    }

    /**
     * 删除域名及关联的配置信息
     *
     * @throws Exception
     */
    @Override
    public void deleteDomainAndConfig(String domainId) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", domainId);

        List<SysConfigPo> configList = sysConfigDao.listByCondition(paramMap);

        //删除配置的模块信息
        String platformCode = sysConfigDao.queryPlatformCodeByDomainId(paramMap);
        paramMap.put("platformCode", platformCode);

        platformModelDao.deletePlatformModel(paramMap);

        //删除配置
        paramMap.clear();
        paramMap.put("domainId", domainId);

        sysConfigDao.deleteByDomainId(paramMap);

        //删除域名主表信息
        sysDomainDao.deleteById(paramMap);
    }

    @Override
    public void deleteSysConfigById(String configId) throws Exception {
        sysConfigDao.deleteById(configId);
    }

    /**
     * 删除所有keyName名称的配置
     *
     * @param keyName
     * @return
     * @throws Exception
     */
    @Override
    public int deleteSysConfigByKeyName(String keyName) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("keyName", keyName);

        return sysConfigDao.deleteByKeyName(paramMap);
    }

    @Override
    public void updateSysConfig(SysConfigPo config) throws Exception {

        sysConfigDao.update(config);
    }

    @Override
    public SysDomain loadSysDomainById(String domainId) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", domainId);

        return sysDomainDao.loadById(paramMap);
    }

    @Override
    public SysConfigPo loadSysConfigById(String configId) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", configId);

        return sysConfigDao.loadById(paramMap);
    }

    /**
     * 查询是否已存在配置,存在返回true
     *
     * @param domainId
     * @param keyName
     * @return
     * @throws Exception
     */
    @Override
    public boolean haveExistConfig(String domainId, String keyName) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", domainId);
        paramMap.put("keyName", keyName);

        List<SysConfigPo> configList = sysConfigDao.listByCondition(paramMap);
        if (configList == null || configList.isEmpty()) {
            return false;
        } else {
            return true;
        }

    }

    @Override
    public List<SysDomain> listSysDomain(Map<String, Object> paramMap) throws Exception {

        return sysDomainDao.listByCondition(paramMap);
    }

    /**
     * 获取目前配置分类信息（每个分类取一条记录）
     *
     * @param domainId
     * @return
     * @throws Exception
     */
    @Override
    public List<SysConfigPo> listConfigType(String domainId) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("domainId", domainId);

        return sysConfigDao.listConfigType(paramMap);
    }


    @Override
    public List<SysConfigPo> queryUserOrgValue() {

        return sysConfigDao.queryUserOrgValue();
    }

    /**
     * 根据平台编码查询授权模块
     */
    @SuppressWarnings("rawtypes")
    @Override
    public List<Map> queryModel(String platformCode) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("platformCode", platformCode);
        return platformModelDao.queryModel(param);
    }

    /**
     * 保存平台模块关联数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public void savePlatformModel(String platformCode, List<String> list) throws Exception {
        Map<String, Object> param1 = new HashMap<String, Object>();
        param1.put("platformCode", platformCode);
        platformModelDao.deletePlatformModel(param1);
        if (list != null && list.size() > 0) {
            Map param = new HashMap();
            param.put("platformCode", platformCode);
            param.put("list", list);
            platformModelDao.insertPlatformModel(param);
        }
    }

    /**
     * @category 保存虚拟平台配置(分销系统专用)
     */
    @Override
    public void saveVirtualPlatformFx(ConfigRequest param) throws Exception {
        //分销管理系统请求的信息内 创建的虚拟平台没有domain domain元素对应内容是一个随机uid
        String d = StringUtils.isEmpty(param.getDomain()) ? GUIDGenerator.getGUID() : param.getDomain();
        this.saveVirtualPlatform(param, d);
    }

    @Override
    public String queryConfigValue(String key, String platformCode, String loginPlatformCode) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("platformCode", platformCode);
        paramMap.put("loginPlatformCode", loginPlatformCode);//查询未使用
        paramMap.put("keyName", key);
        String dataValue = sysConfigDao.queryValueByPlatformCodeAndKeyName(paramMap);
        return dataValue;
    }

    @Override
    public List<TbSysEduResPlatform> getEduResParam(Map<String, Object> param) {
        return sysConfigDao.getEduResParam(param);
    }

    @Override
    public List<Map<String, Object>> getTbSysConfigOthers(Map<String, Object> param) {
        return sysConfigDao.getTbSysConfigOthers(param);
    }

    @Override
    public String queryPlatformDomain(Map<String, Object> param) {
        return sysDomainDao.queryPlatformDomain(param);
    }

    @Override
    public String queryConfigValueByDomainId(Map<String, Object> paramMap) {
        return sysConfigDao.queryConfigValueByDomainId(paramMap);
    }

    @Override
    public SysDomain getSysDomain(String domain) {
        return sysDomainDao.getSysDomain(domain);
    }
}
